/**
 *
 * LICENSE: Some license information
 *
 * @author Konstantin Chumachneko
 */
 
/**
 * @var custvox.userlist - Определение пространства имен проекта.
 * Глобальный объект.
 */
var phonebook = {	
		model: {},
		view: {},
		controller: {}	
};
/**
 * Класс таблиц базы данных для панели администрирования
 * @lends phonebook.view.AdminView
 */
phonebook.view.AdminView = Base.extend({
	
    controller : null,		// объект управления процессами Приложения
    contextMenu: null,
    orgUnitTypeTable: null,
    orgUnitTable: null,
    postTable: null,
    phoneTypeTable: null,
    phoneTable: null,
    roomTable: null,
    personTable: null,
    orgUnitPostTable: null,
    /**
     * Конструктор класса
     * @author Konstantin Chumachenko
     * 
     * @augments Base
     * @class Класс таблиц базы данных для панели администрирования
     * 
     * <p><b>Пример:</b></p>
     * <pre class="code">
     * var AdminView = new phonebook.view.AdminView(controller);
     * </pre>
     * 
     * @constructs
     * @param {Controller} controller Контроллер приложения.
     */
    constructor : function(controller) {	
        console.log("-- AdminView: Конструктор.");
        this.controller = controller;
        this.domElement = $(MAIN_HOLDER);
        this.render(this.domElement);
    },
	
    /**
     * Возвращает DOM-элемент этой панели 
     * @function
     * @public 
     * @memberOf phonebook.view.AdminView#
     */
    getDomElement : function() {
        return this.domElement;
    },
	
    /**
     * Выполняется отрисовка.
     * @private 
     * @function
     * @param (elementDOM) renderTo Элемент DOM, внутри которого будет создан контейнер.
     * @return none
     */
    render : function(renderTo) {
        console.log("-- AdminView2: render.");
        var me = this;      
        var model = me.controller.bigModel.getModel();
        var turnText = "[TURN]";
        var orgUnitType = 1,
        orgUnit = 1,
        post = 1,
        phoneType = 1,
        phone = 1,
        room = 1,
        person = 1,
        orgUnitPost = 1;
        me.contextMenu = new widget.PopupMenu({
            width : 200,
            items : [             
            {
              value:2,
              text:"Добавить"
            },
            {                
                value:1, 
                text:'Удалить'
            }
            ],
            listeners : {
                select : function(menu, menuItem, gridRecord){
                    if (menuItem.value==1){
                        me.controller.deleteById(gridRecord[0],gridRecord.pop());
                    }
                     if (menuItem.value==2){
                        me.controller.showAddDialog(gridRecord.pop());
                    }
                }
            }
        });
        /**
         * Таблица OrgUnitType
         */
        $(ORG_UNIT_TYPE_TABLE_HOLDER).append( '<h3 id="tblHeader">OrgUnitType</h3>');
        new widget.ActiveLink({
            text : turnText,
            renderTo: ORG_UNIT_TYPE_TABLE_HOLDER,
            listeners : {
                click : function(lnk, elementDom){
                    if (orgUnitType==1){
                        orgUnitType = 0;                    
                        $("#orgUnitType_wrapper").hide();    
                    }else{
                        orgUnitType = 1;                    
                        $("#orgUnitType_wrapper").show();    
                    }
                    
                }
            }
        });
        
        $(ORG_UNIT_TYPE_TABLE_HOLDER).append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="orgUnitType"></table>' );
        me.orgUnitTypeTable = $('#orgUnitType').dataTable( {
            "bFilter": false,                
            "aaData":model["orgUnitType"],
            "fnRowCallback":function( nRow, aData, iDisplayIndex ) {
                $(nRow).bind('contextmenu', function(event) {
                    me.onContextMenu(aData, nRow, event,"OrgUnitType");
                    return false;
                });
                
            }, 
            "aoColumns": [
            {
                "sTitle": "id"
            },
            {
                "sTitle": "name"
            }
            ]
        } );   
        
        /**
         * Таблица OrgUnit
         */
        $(ORG_UNIT_TABLE_HOLDER).append( '<h3 id="tblHeader">OrgUnit</h3>');
        new widget.ActiveLink({
            text : turnText,
            renderTo: ORG_UNIT_TABLE_HOLDER,
            listeners : {
                click : function(lnk, elementDom){
                    if (orgUnit==1){
                        orgUnit = 0;                    
                        $("#orgUnit_wrapper").hide();    
                    }else{
                        orgUnit = 1;                    
                        $("#orgUnit_wrapper").show();    
                    }
                    
                }
            }
        });
        $(ORG_UNIT_TABLE_HOLDER).append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="orgUnit"></table>' );
        me.orgUnitTable = $('#orgUnit').dataTable( {
            "bFilter": false,     
            "aaData":model["orgUnit"],
            "fnRowCallback":function( nRow, aData, iDisplayIndex ) {
                $(nRow).bind('contextmenu', function(event) {
                    me.onContextMenu(aData, nRow, event,"OrgUnit");
                    return false;
                });
                
            }, 
            "aoColumns": [
            {
                "sTitle": "id"
            },
            {
                "sTitle": "name"
            },
            {
                "sTitle": "unitType ID"
            },
            {
                "sTitle": "perent unit id"
            }
            ]
        } );   
        /**
         * Таблица Post
         */          
        $(POST_TABLE_HOLDER).append( '<h3 id="tblHeader">Post</h3>');
        new widget.ActiveLink({
            text : turnText,
            renderTo: POST_TABLE_HOLDER,
            listeners : {
                click : function(lnk, elementDom){
                    if (post==1){
                        post = 0;                    
                        $("#post_wrapper").hide();    
                    }else{
                        post = 1;                    
                        $("#post_wrapper").show();    
                    }
                    
                }
            }
        });
        $(POST_TABLE_HOLDER).append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="post"></table>' );
        me.postTable = $('#post').dataTable( {
            "bFilter": false,     
            "aaData":model["post"],
            "fnRowCallback":function( nRow, aData, iDisplayIndex ) {
                $(nRow).bind('contextmenu', function(event) {
                    me.onContextMenu(aData, nRow, event,"Post");
                    return false;
                });
            }, 
            "aoColumns": [
            {
                "sTitle": "id"
            },
            {
                "sTitle": "name"
            }
            ]
        } );   
        /**
         * Таблица PhoneType
         */          
        $(PHONE_TYPE_TABLE_HOLDER).append( '<h3 id="tblHeader">PhoneType</h3>');
        new widget.ActiveLink({
            text : turnText,
            renderTo: PHONE_TYPE_TABLE_HOLDER,
            listeners : {
                click : function(lnk, elementDom){
                    if (phoneType==1){
                        phoneType = 0;                    
                        $("#phoneType_wrapper").hide();    
                    }else{
                        phoneType = 1;                    
                        $("#phoneType_wrapper").show();    
                    }
                    
                }
            }
        });
        $(PHONE_TYPE_TABLE_HOLDER).append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="phoneType"></table>' );
        me.phoneTypeTable = $('#phoneType').dataTable( {
            "bFilter": false,     
            "aaData":model["phoneType"],
            "fnRowCallback":function( nRow, aData, iDisplayIndex ) {
                $(nRow).bind('contextmenu', function(event) {
                    me.onContextMenu(aData, nRow, event,"PhoneType");
                    return false;
                });
            }, 
            "aoColumns": [
            {
                "sTitle": "id"
            },
            {
                "sTitle": "name"
            }
            ]
        } );   
        /**
         * Таблица Phone
         */
        $(PHONE_TABLE_HOLDER).append( '<h3 id="tblHeader">Phone</h3>');
        new widget.ActiveLink({
            text : turnText,
            renderTo: PHONE_TABLE_HOLDER,
            listeners : {
                click : function(lnk, elementDom){
                    if (phone==1){
                        phone = 0;                    
                        $("#phone_wrapper").hide();    
                    }else{
                        phone = 1;                    
                        $("#phone_wrapper").show();    
                    }
                    
                }
            }
        });
        $(PHONE_TABLE_HOLDER).append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="phone"></table>' );
        me.phoneTable = $('#phone').dataTable( {
            "bFilter": false,     
            "aaData":model["phone"],
            "fnRowCallback":function( nRow, aData, iDisplayIndex ) {
                $(nRow).bind('contextmenu', function(event) {
                    me.onContextMenu(aData, nRow, event,"Phone");
                    return false;
                });
            }, 
            "aoColumns": [
            {
                "sTitle": "id"
            },
            {
                "sTitle": "number"
            },
            {
                "sTitle": "UnitPost Id"
            },
            {
                "sTitle": "PhoneType Id"
            }
            ]
        } );   
        /**
         * Таблица Room
         */
        $(ROOM_TABLE_HOLDER).append('<h3 id="tblHeader">Room</h3>');
        new widget.ActiveLink({
            text : turnText,
            renderTo: ROOM_TABLE_HOLDER,
            listeners : {
                click : function(lnk, elementDom){
                    if (room==1){
                        room = 0;                    
                        $("#room_wrapper").hide();    
                    }else{
                        room = 1;                    
                        $("#room_wrapper").show();    
                    }
                    
                }
            }
        });
        $(ROOM_TABLE_HOLDER).append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="room"></table>' );
        me.roomTable = $('#room').dataTable( {
            "bFilter": false,     
            "aaData":model["room"],
            "fnRowCallback":function( nRow, aData, iDisplayIndex ) {
                $(nRow).bind('contextmenu', function(event) {
                    me.onContextMenu(aData, nRow, event,"Room");
                    return false;
                });
            }, 
            "aoColumns": [
            {
                "sTitle": "id"
            },
            {
                "sTitle": "name"
            }
            ]
        } );   
        /**
         * Таблица Person        
         */
        $(PERSON_TABLE_HOLDER).append( '<h3 id="tblHeader">Person</h3>');
        new widget.ActiveLink({
            text : turnText,
            renderTo: PERSON_TABLE_HOLDER,
            listeners : {
                click : function(lnk, elementDom){
                    if (person==1){
                        person = 0;                    
                        $("#person_wrapper").hide();    
                    }else{
                        person = 1;                    
                        $("#person_wrapper").show();    
                    }
                    
                }
            }
        });
        $(PERSON_TABLE_HOLDER).append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="person"></table>' );
        me.personTable = $('#person').dataTable( {
            "bFilter": false,     
            "aaData":model["person"],
            "fnRowCallback":function( nRow, aData, iDisplayIndex ) {
                $(nRow).bind('contextmenu', function(event) {
                    me.onContextMenu(aData, nRow, event,"Person");
                    return false;
                });
            }, 
            "aoColumns": [
            {
                "sTitle": "id"
            },
            {
                "sTitle": "surname"
            },
            {
                "sTitle": "name"
            },
            {
                "sTitle": "patronymic"
            }
            
            ]
        } );   
        
        /**
         * Таблица orgUnitPost      
         * id, unit id, person id, post id, room id.   
         */
        $(ORG_UNIT_POST_TABLE_HOLDER).append( '<h3 id="tblHeader">OrgUnitPost </h3>');
        new widget.ActiveLink({
            text : turnText,
            renderTo: ORG_UNIT_POST_TABLE_HOLDER,
            listeners : {
                click : function(lnk, elementDom){
                    if (orgUnitPost==1){
                        orgUnitPost = 0;                    
                        $("#orgUnitPost_wrapper").hide();    
                    }else{
                        orgUnitPost = 1;                    
                        $("#orgUnitPost_wrapper").show();    
                    }
                    
                }
            }
        });
        $(ORG_UNIT_POST_TABLE_HOLDER).append('<table cellpadding="0" cellspacing="0" border="0" class="display" id="orgUnitPost"></table>' );        
        me.orgUnitPostTable = $('#orgUnitPost').dataTable( {
            "bFilter": false,     
            "aaData":model["orgUnitPost"],
            "fnRowCallback":function( nRow, aData, iDisplayIndex ) {
                $(nRow).bind('contextmenu', function(event) {
                    me.onContextMenu(aData, nRow, event,"OrgUnitPost");
                    return false;
                });
            }, 
            "aoColumns": [
            {
                "sTitle": "id"
            },
            {
                "sTitle": "unit id"
            },
            {
                "sTitle": "person id"
            },
            {
                "sTitle": "room id"
            },
            {
                "sTitle": "post id"
            }
            ]
        } );
    },
    onContextMenu : function(record, element, event, table) {        
        record.push(table);
        var menu = this.contextMenu;	
        var position = {
            x : event.pageX, 
            y : event.pageY
        };
        menu.render(position, record);
    }
	
});/**
 * Класс таблицы списка.
 * @lends phonebook.view.SidebarView
 */
phonebook.view.SidebarView = Base.extend({
	
    controller : null,		// объект управления процессами Приложения   
	
    /**
     * Конструктор класса
     * @author Konstantin Chumachenko
     * 
     * @augments Base
     * @class Класс панели списка пользователей.
     * 
     * <p><b>Пример:</b></p>
     * <pre class="code">
     * var SidebarView = new phonebook.view.SidebarView(controller);
     * </pre>
     * 
     * @constructs
     * @param {Controller} controller Контроллер приложения.
     */
    constructor : function(controller) {	
        console.log("-- SidebarView: Конструктор.");
        this.controller = controller;
        this.domElement = $(SIDEBAR_HOLDER);
        this.render(this.domElement);
    },
	
    /**
     * Возвращает DOM-элемент этой панели 
     * @function
     * @public 
     * @memberOf phonebook.view.SidebarView#
     */
    getDomElement : function() {
        return this.domElement;
    },
	
    /**
     * Выполняется отрисовка панели.
     * @private 
     * @function
     * @param (elementDOM) renderTo Элемент DOM, внутри которого будет создан контейнер.
     * @return none
     */
    render : function(renderTo) {
        console.log("-- SidebarView: render!.");
        var me = this;
        new widget.Button({
            text : 'OrgUnitType',
            cls : 'btnCommon',
            width: 115,
            renderTo: renderTo,
            listeners : {
                click : function(btn, elementDom){
                    me.controller.addDialog.orgUnitType.render();
                }
            }
        });
            
        new widget.Button({
            text : 'OrgUnit',
            cls : 'btnCommon',
            width: 115,
            width: 115,
            renderTo: renderTo,
            listeners : {
                click : function(btn, elementDom){
                    me.controller.addDialog.orgUnit.render();
                }
            }
        });
        new widget.Button({
            text : 'Post',
            cls : 'btnCommon',
            width: 115,
            renderTo: renderTo,
            listeners : {
                click : function(btn, elementDom){
                    me.controller.addDialog.post.render();  
                }
            }
        });
        new widget.Button({
            text : 'PhoneType',
            cls : 'btnCommon',
            width: 115,
            renderTo: renderTo,
            listeners : {
                click : function(btn, elementDom){
                    me.controller.addDialog.phoneType.render();
                }
            }
        });
        new widget.Button({
            text : 'Phone',
            cls : 'btnCommon',
            width: 115,
            renderTo: renderTo,
            listeners : {
                click : function(btn, elementDom){
                    me.controller.addDialog.phone.render();
                }
            }
        });
        new widget.Button({
            text : 'Room',
            cls : 'btnCommon',
            width: 115,
            renderTo: renderTo,
            listeners : {
                click : function(btn, elementDom){
                    me.controller.addDialog.room.render();
                }
            }
        });
        new widget.Button({
            text : 'Person',
            cls : 'btnCommon',
            renderTo: renderTo,
            width: 115,
            listeners : {
                click : function(btn, elementDom){
                    me.controller.addDialog.person.render();
                }
            }
        });
        new widget.Button({
            text : 'OrgUnitPost',
            width: 115,
            cls : 'btnCommon',
            renderTo: renderTo,
            listeners : {
                click : function(btn, elementDom){
                    me.controller.addDialog.orgUnitPost.render();
                }
            }
        });
    }
	
});/**
 * Класс таблицы списка.
 * @lends phonebook.view.AddNewDialog
 */
phonebook.view.AddNewDialog = Base.extend({
	
    controller : null,		// объект управления процессами Приложения      
    orgUnitType: null,
    orgUnit:null,
    post:null,
    person: null,
    phoneType: null,
    phone: null,
    room: null,
    orgUnitPost:null,
    /**
     * Конструктор класса
     * @author Konstantin Chumachenko
     * 
     * @augments Base
     * @class Класс панели списка пользователей.
     * 
     * <p><b>Пример:</b></p>
     * <pre class="code">
     * var AddNewDialog = new phonebook.view.AddNewDialog(controller);
     * </pre>
     * 
     * @constructs
     * @param {Controller} controller Контроллер приложения.
     */
    constructor : function(controller) {	
        console.log("-- AddNewDialog: Конструктор.");
        this.controller = controller;
        this.domElement = $(SIDEBAR_HOLDER);
        this.render(this.domElement);
    },
	
    /**
     * Возвращает DOM-элемент этой панели 
     * @function
     * @public 
     * @memberOf phonebook.view.AddNewDialog#
     */
    getDomElement : function() {
        return this.domElement;
    },
	
    /**
     * Выполняется отрисовка панели.
     * @private 
     * @function
     * @param (elementDOM) renderTo Элемент DOM, внутри которого будет создан контейнер.
     * @return none
     */
    render : function(renderTo) {
        console.log("-- AddNewDialog: render.");
        var me = this;
        /*
         * orgUniTypeName
         */
        var orgUnitTypeName = new widget.Text({
            id: 'name',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'Name:'
            }
        });
        /*
         * OrgUnitTypeId
         */
        var orgUnitTypeId = new widget.Text({
            id: 'unitTypeId',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'OrgUnitType id:'
            }
        });
        /*
         * perentUnitId
         */
        var orgUnitId = new widget.Text({
            id: 'perentUnitId',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'PerentUnit id:'
            }
        });
        /*
         * perentUnitId
         */
        var orgUnitPostId = new widget.Text({
            id: 'orgUnitPostId',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'UnitPost id:'
            }
        });
        /*
         * phoneType
         */
        var phoneType = new widget.Text({
            id: 'phoneType',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'phoneType id:'
            }
        });
        /*
         * phoneNumber
         */
        var phoneNumber = new widget.Text({
            id: 'phoneNumber',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'phoneNumber:'
            }
        });
        /*
         * roomName
         */
        var roomName = new widget.Text({
            id: 'roomName',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'room name:'
            }
        });
        /*
         * Name
         */
        var name = new widget.Text({
            id: 'name',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'Name:'
            }
        });
        /*
         * surname
         */
        var surname = new widget.Text({
            id: 'surname',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'Surname:'
            }
        });
        /*
         * surname
         */
        var patronymic = new widget.Text({
            id: 'patronymic',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "right",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'Patronymic:'
            }
        });
        /*
         * Person ID
         */
        var personId = new widget.Text({
            id: 'personId',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'Person ID:'
            }
        });
        /*
         * Room ID
         */
        var roomId = new widget.Text({
            id: 'roomId',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'Room ID:'
            }
        });
        /*
         * Post ID
         */
        var postId = new widget.Text({
            id: 'postId',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'Post ID:'
            }
        });
        var phoneTypeName = new widget.Text({
            id: 'phoneTypeName',
            cls: "inp",
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "right",
                text: 'Phone Type Name:'
            }
        });
        /*
         * OrgUnitType dialog
         */
        me.orgUnitType = new widget.Dialog({
            title : 'Add orgUnitPost',
            modal : true,
            height: 200,
            width : 400,
            cls : 'content',
            items :  [orgUnitTypeName,"<div id='orgUnitPostError'></div>"],
            buttons: [
            {
                text: "Добавить",
                click: function() {
                    var data={
                        name:orgUnitTypeName.value
                    };
                    me.controller.addOrgUnitType(data);
                }
            },
            {
                text: "Отмена",
                click: function() {
                    me.orgUnitType.close();
                }
            }
            ]
        });
        /*
         * orgUnit dialog
         */
        me.orgUnit = new widget.Dialog({
            title : 'Add orgUnit',
            modal : true,
            height: 300,
            width : 400,
            cls : 'content',
            items :  [orgUnitTypeName,orgUnitTypeId,orgUnitId,"<div id='orgUnitError'></div>"],
            buttons: [
            {
                text: "Добавить",
                click: function() {
                    var data={
                        name:orgUnitTypeName.value,
                        unitType: orgUnitTypeId.value,
                        perent:orgUnitId.value
                    };
                    me.controller.addOrgUnit(data);
                }
            },
            {
                text: "Отмена",
                click: function() {
                    me.orgUnit.close();
                }
            }
            ]
        });
        /*
         * post dialog
         */
        me.post = new widget.Dialog({
            title : 'Add Post',
            modal : true,
            height: 300,
            width : 300,
            cls : 'content',
            items :  [orgUnitTypeName,"<div id='postError'></div>"],
            buttons: [
            {
                text: "Добавить",
                click: function() {
                    var data={
                        name:orgUnitTypeName.value        
                    };
                    me.controller.addPost(data);
                }
            },
            {
                text: "Отмена",
                click: function() {
                    me.post.close();
                }
            }
            ]
        });
        /*
         * phoneType dialog
         */
        me.phoneType = new widget.Dialog({
            title : 'Add phone type',
            modal : true,
            height: 300,
            width : 350,
            cls : 'content',
            items :  [phoneTypeName,"<div id='phoneTypeError'></div>"],
            buttons: [
            {
                text: "Добавить",
                click: function() {
                    var data={
                        name:phoneTypeName.value                     
                    };
                    me.controller.addPhoneType(data);
                }
            },
            {
                text: "Отмена",
                click: function() {
                    me.phoneType.close();
                }
            }
            ]
        });
        /*
         * phone dialog
         */
        me.phone = new widget.Dialog({
            title : 'Add phone',
            modal : true,
            height: 300,
            width : 350,
            cls : 'content',
            items :  [phoneNumber,orgUnitPostId,phoneType,"<div id='phoneError'></div>"],
            buttons: [
            {
                text: "Добавить",
                click: function() {
                    var data={
                        number:phoneNumber.value,
                        unitPost:orgUnitPostId.value,
                        type:phoneType.value
                    };
                    me.controller.addPhone(data);
                }
            },
            {
                text: "Отмена",
                click: function() {
                    me.phone.close();
                }
            }
            ]
        });
        /*
         * room dialog
         */
        me.room = new widget.Dialog({
            title : 'Add room',
            modal : true,
            height: 300,
            width : 350,
            cls : 'content',
            items :  [roomName,"<div id='roomError'></div>"],
            buttons: [
            {
                text: "Добавить",
                click: function() {
                    var data={
                        name:roomName.value
                    };
                    me.controller.addRoom(data);
                }
            },
            {
                text: "Отмена",
                click: function() {
                    me.room.close();
                }
            }
            ]
        });
        /*
         * person dialog
         */
        me.person = new widget.Dialog({
            title : 'Add person',
            modal : true,
            height: 300,
            width : 350,
            cls : 'content',
            items :  [name,surname,patronymic,"<div id='personError'></div>"],
            buttons: [
            {
                text: "Добавить",
                click: function() {
                    var data={
                        name:name.value,
                        surname: surname.value,
                        patronymic: patronymic.value
                    };
                    me.controller.addPerson(data);
                }
            },
            {
                text: "Отмена",
                click: function() {
                    me.person.close();
                }
            }
            ]
        });
        /*
         * orgUnitPost dialog
         */
        me.orgUnitPost = new widget.Dialog({
            title : 'Add orgUnitPost',
            modal : true,
            height: 300,
            width : 350,
            cls : 'content',
            items :  [orgUnitId,personId,roomId,postId,"<div id='orgUnitPostError'></div>"],
            buttons: [
            {
                text: "Добавить",
                click: function() {
                    var data={
                        orgUnitId:orgUnitId.value,
                        personId: personId.value,
                        roomId: roomId.value,
                        postId: postId.value
                    };
                    me.controller.addOrgUnitPost(data);
                }
            },
            {
                text: "Отмена",
                click: function() {
                    me.orgUnitPost.close();
                }
            }
            ]
        });
    }
});/**
 * Класс таблицы списка.
 * @lends phonebook.view.AdderView
 */
phonebook.view.AdderView = Base.extend({
	
    controller : null,		// объект управления процессами Приложения   
	
    /**
     * Конструктор класса
     * @author Konstantin Chumachenko
     * 
     * @augments Base
     * @class Класс панели списка пользователей.
     * 
     * <p><b>Пример:</b></p>
     * <pre class="code">
     * var AdderView = new phonebook.view.AdderView(controller);
     * </pre>
     * 
     * @constructs
     * @param {Controller} controller Контроллер приложения.
     */
    constructor : function(controller) {	
        console.log("-- AdderView: Конструктор3.");
        this.controller = controller;
        this.domElement = $(ADDER_HOLDER);
        this.render(this.domElement);
    },
	
    /**
     * Возвращает DOM-элемент этой панели 
     * @function
     * @public 
     * @memberOf phonebook.view.AdderView#
     */
    getDomElement : function() {
        return this.domElement;
    },
	
    /**
     * Выполняется отрисовка панели.
     * @private 
     * @function
     * @param (elementDOM) renderTo Элемент DOM, внутри которого будет создан контейнер.
     * @return none
     */
    render : function(renderTo) {
        console.log("-- AdderView: render!.");
        var me = this;
        var model =me.controller.bigModel.getModel();
   
        
        var adderSurname = new widget.Text({
            id: 'surname',
            cls: "inp",
            renderTo: ADDER_FIRST_HOLDER,
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "left",
                text: 'Призвище:'
            }
        });
           
        var adderName = new widget.Text({
            id: 'name',
            cls: "inp",
            renderTo: ADDER_FIRST_HOLDER,
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "left",
                text: "Ім'я:"
            }
        });
        var adderPatronymic = new widget.Text({
            id: 'patronymic',
            cls: "inp",
            renderTo: ADDER_FIRST_HOLDER,
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 130,
                align: "left",
                text: 'По батькові:'
            }
        });
        
        var adderTelephone = new widget.Text({
            id: 'telephone',
            cls: "inp",
            renderTo: ADDER_SECOND_HOLDER,
            input : {
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 80,
                align: "left",
                text: 'Телефон:'
            }
        });
        var adderTelephoneType = new widget.Text({
            id: 'telephone_type',
            cls: "inp",
            renderTo: ADDER_SECOND_HOLDER,
            input : {
                id:'phoneTypeInput',
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 80,
                align: "left",
                text: 'Тип:'
            }
        });
        
        $("#phoneTypeInput").autocomplete({
            source: me.getArrayFromModel(model.phoneType)
        });
        
        var adderRoom = new widget.Text({
            id: 'room',
            cls: "inp",
            renderTo: ADDER_THIRD_HOLDER,
            input : {
                id: 'roomInput',
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 80,
                align: "left",
                text: '№ Ауд.:'
            }
        });
        
        $("#roomInput").autocomplete({
            source: me.getArrayFromModel(model.room)
        });
        
        var adderUnit = new widget.Text({
            id: 'unit',
            cls: "inp",
            renderTo: ADDER_THIRD_HOLDER,
            input : {
                id: 'unitInput',
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 80,
                align: "left",
                text: 'Підрозділ:'
            }
        });
        
        $("#unitInput").autocomplete({
            source: me.getArrayFromModel(model.orgUnit)
        });
        
             var adderPost = new widget.Text({
            id: 'post',
            cls: "inp",
            renderTo: ADDER_THIRD_HOLDER,
            input : {
                id:"postInput",
                cls : 'inp',
                align: "left",
                width : 130
            },
            label:{
                width : 80,
                align: "left",
                text: 'Посада:'
            }
           
        });
        
        $("#postInput").autocomplete({
            source: me.getArrayFromModel(model.post)
        });
        
        var adderButton = new widget.Button({
            id: 'add',
            cls: "inp",
            renderTo: ADDER_BUTTON_HOLDER,
            text:  "Додати",
            listeners: {
                click: function(btn,  elementDom){
                    var data={
                        post: adderPost.value,
                        surname: adderSurname.value,
                        name: adderName.value,
                        patronymic: adderPatronymic.value,
                        phone: adderTelephone.value,
                        phoneType: adderTelephoneType.value,
                        room: adderRoom.value,
                        unit: adderUnit.value
                    }
                    me.controller.addFromAdder(data);
                }
            }
        });
    },
    getArrayFromModel: function(model){
        var answer=[];
        var length = model.length;
        for(var i=0;i<length;i++){
            answer.push(model[i][1]);
        }
        return answer;
    }
});/**
 * Это класс управления процессами Приложения.
 * @lends phonebook.controller.Controller
 */
phonebook.controller.Controller = Base.extend({

    adminView: null,
    bigModel: null,
    sidebar: null,
    addDialog: null,
    adder:null,
    /**
     * Конструктор класса
     * @author Konstantin Chumachenko
     * @augments Base
     * @class Класс управления процессами Приложения.
     * 
     * @constructs
     */
    constructor : function() {
        console.log("-- Controller: Конструктор4.");
        var me = this;
        me.bigModel = new phonebook.model.AutocompleteModel(me);
        me.bigModel.load();
        me.adminView = new phonebook.view.AdminView(me);
        me.sidebar = new phonebook.view.SidebarView(me);
        me.addDialog = new phonebook.view.AddNewDialog(me);
        me.adder = new phonebook.view.AdderView(me);
    },
    /**
     * Добавление в таблицу OrgUnitType
     */
    addOrgUnitType: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addOrgUnitType',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){             
                me.addDialog.orgUnitType.close();          
                me.refreshOrgUnitType();
                console.log("success");
            }
        });
    },
    /**
     * Добавление в таблицу OrgUnit
     */
    addOrgUnit: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addOrgUnit',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){             
                me.addDialog.orgUnit.close();          
                me.refreshOrgUnit();
                console.log("success");
            }
        });
    },
    /**
     * Добавление в таблицу Post
     */
    addPost: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addPost',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){             
                me.addDialog.post.close();          
                me.refreshPost();
                console.log("success");
            }
        });  
    },
    /**
     * Добавление в таблицу PhoneType
     */
    addPhoneType: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addPhoneType',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){             
                me.addDialog.phoneType.close();          
                me.refreshPhoneType();
                console.log("success");
            }
        });  
    },
    /**
     * Добавление в Phone
     */
    addPhone: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addPhone',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){             
                me.addDialog.phone.close();          
                me.refreshPhone();
                console.log("success");
            }
        });  
    },
    /**
     * Добавление в Room
     */
    addRoom: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addRoom',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){             
                me.addDialog.room.close();          
                me.refreshRoom();
                console.log("success");
            }
        });  
    },
    /**
     * Добавление в Person
     */
    addPerson: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addPerson',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){             
                me.addDialog.person.close();          
                me.refreshPerson();
                console.log("success");
            }
        });  
    },
    /**
     * Добавление в OrgUnitPost
     */
    addOrgUnitPost: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addOrgUnitPost',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){             
                me.addDialog.orgUnitPost.close();          
                me.refreshOrgUnitPost();
                console.log("success");
            }
        });  
    },
    addFromAdder: function(data){
        var me=this;
        $.ajax({
            type: 'POST',
            url: 'index?ajax=admin&query=addAll',
            data: data,
            async: false,
            success: function(data,  textStatus,  jqXHR){
                console.log("success");
                me.refreshAll();
            }
        });  
    },
    /**
     * Удаление из таблицы table по id
     * @param id
     * @param table
     */
    deleteById: function(id,table){
        var me=this;
        console.log(id);
        console.log(table);       
        $.ajax({
            type: 'POST',
            dataType: "json",
            url: 'index?ajax=admin&query=delete'+table,
            data: {
                "id": id
            },
            async: false,
            success: function(data,  textStatus,  jqXHR){
                if (data.error == undefined){
                    if (table == "OrgUnitType"){
                        me.refreshOrgUnitType();
                    }  
                    if (table == "OrgUnit"){                        
                        me.refreshOrgUnit();
                    }    
                    if (table == "Post"){
                        me.refreshPost();
                    } 
                    if (table == "PhoneType"){
                        me.refreshPhoneType();
                    }  
                    if (table == "Phone"){
                        me.refreshPhone();
                    }    
                    if (table == "Room"){
                        me.refreshRoom();
                    }
                    if (table == "Person"){
                        me.refreshPerson();
                    }
                    if (table == "OrgUnitPost"){
                        me.refreshOrgUnitPost();
                    }
                }else{
                    jAlert(data.error,"Ошибка");
                }
            }
        });
      
    },
    /**
     * Открытие диалого добавление в таблицу
     * @param table Таблица
     */
    showAddDialog: function(table){
        var me = this;
        if (table == "OrgUnitType"){
            me.addDialog.orgUnitType.render();
        }  
        if (table == "OrgUnit"){                        
            me.addDialog.orgUnit.render();
        }    
        if (table == "Post"){
            me.addDialog.post.render();
        } 
        if (table == "PhoneType"){
            me.addDialog.phoneType.render();
        }  
        if (table == "Phone"){
            me.addDialog.phone.render();
        }    
        if (table == "Room"){
            me.addDialog.room.render();
        }
        if (table == "Person"){
            me.addDialog.person.render();
        }
        if (table == "OrgUnitPost"){
            me.addDialog.orgUnitPost.render();
        }
    },
    refreshAll: function(){
        this.bigModel.load();  
        var model = this.bigModel.getModel();
        this.adminView.orgUnitTypeTable.fnClearTable();
        this.adminView.orgUnitTypeTable.fnAddData(model["orgUnitType"]);
        this.adminView.orgUnitTable.fnClearTable();
        this.adminView.orgUnitTable.fnAddData(model["orgUnit"]);
        this.adminView.postTable.fnClearTable();
        this.adminView.postTable.fnAddData(model["post"]);
        this.adminView.phoneTypeTable.fnClearTable();
        this.adminView.phoneTypeTable.fnAddData(model["phoneType"]);
        this.adminView.phoneTable.fnClearTable();
        this.adminView.phoneTable.fnAddData(model["phone"]);
        this.adminView.roomTable.fnClearTable();
        this.adminView.roomTable.fnAddData(model["room"]);
        this.adminView.personTable.fnClearTable();
        this.adminView.personTable.fnAddData(model["person"]);
        this.adminView.orgUnitPostTable.fnClearTable();
        this.adminView.orgUnitPostTable.fnAddData(model["orgUnitPost"]);
    },
    refreshOrgUnitType: function(){
        this.bigModel.load();  
        var model = this.bigModel.getModel()["orgUnitType"];
        this.adminView.orgUnitTypeTable.fnClearTable();
        this.adminView.orgUnitTypeTable.fnAddData(model);
    },
    refreshOrgUnit: function(){
        this.bigModel.load();
        var model = this.bigModel.getModel()["orgUnit"];
        this.adminView.orgUnitTable.fnClearTable();
        this.adminView.orgUnitTable.fnAddData(model);
    },
    refreshPost: function(){
        this.bigModel.load();
        var model = this.bigModel.getModel()["post"];
        this.adminView.postTable.fnClearTable();
        this.adminView.postTable.fnAddData(model);
    },
    refreshPhoneType: function(){
        this.bigModel.load();
        var model = this.bigModel.getModel()["phoneType"];
        this.adminView.phoneTypeTable.fnClearTable();
        this.adminView.phoneTypeTable.fnAddData(model);
    },
    refreshPhone: function(){
        this.bigModel.load();
        var model = this.bigModel.getModel()["phone"];
        this.adminView.phoneTable.fnClearTable();
        this.adminView.phoneTable.fnAddData(model);
    },
    refreshRoom: function(){
        this.bigModel.load();
        var model = this.bigModel.getModel()["room"];
        this.adminView.roomTable.fnClearTable();
        this.adminView.roomTable.fnAddData(model);
    },
    refreshPerson: function(){
        this.bigModel.load();
        var model = this.bigModel.getModel()["person"];
        this.adminView.personTable.fnClearTable();
        this.adminView.personTable.fnAddData(model);
    },
    refreshOrgUnitPost: function(){
        this.bigModel.load();
        var model = this.bigModel.getModel()["orgUnitPost"];
        this.adminView.orgUnitPostTable.fnClearTable();
        this.adminView.orgUnitPostTable.fnAddData(model);
    }
});
/**
 * Это класс модели пользователя.
 * @lends phonebook.model.AutocompleteModel
 */
phonebook.model.AutocompleteModel = Base.extend({

    controller : null,		// объект управления процессами Приложения
    bigModel: null,
        
    /**
     * Конструктор класса
     * @author Konstantin Chumachenko
     * @class Класс модели списка книг.
     * 
     * <p><b>Пример:</b></p>
     * <pre class="code">
     * var AutocompleteModel = new phonebook.model.AutocompleteModel(controller);
     * AutocompleteModel.load();
     * </pre>
     * 
     * @constructs
     * @param {Controller} controller Контроллер приложения.
     */
    constructor : function(controller) {
        console.log('-- AutocompleteModel: Конструктор.');
        this.controller = controller;
    },
	
    /**
     * Загрузить данные модели таблицы.
     * @public 
     * @function 
     * @memberOf phonebook.model.AutocompleteModel#
     */
    load: function() {
        var me = this;
        try {		
            $.ajax({
                type: 'POST',
                url: 'index?ajax=admin&query=getAutocomplete',
                async: false,
                success: function(data,  textStatus,  jqXHR){
                    var com =  jQuery.parseJSON(data);                   
                    me.bigModel = com;
                }
            });
        }
        catch (e) {
            throw 'phonebook.model.AutocompleteModel::load(): '+e;
        }
    },
    getModel: function(){
        return this.bigModel;
    }
});
/**
 * Старт.
 * Запуск приложения после загрузки странички
 */
$(document).ready(function () {
	
	/* Вспомогательная функция форматирования строк сообщений.
	 * Пример:
	 *   alert("Hello {name}".format({ name: 'World' }));
	 */
	String.prototype.format = function (args) {
    	var newStr = this;
    	for (var key in args) {
        	newStr = newStr.replace('{' + key + '}', args[key]);
    	}
    	return newStr;
	}

	/*
	 * Теперь стартуем ...
	 */
	try {
		var controller = new phonebook.controller.Controller();
	}
	catch (e) {
		alert("Exception:\n\n" + e);
	}
});

